﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.astd.common.manager;
using com.lover.common.json;
using com.lover.common.http;

namespace com.lover.astd.common.partner.impl
{
    public class AoshitangLogin : LoginImplBase
    {
        public AoshitangLogin() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            HttpResult resp;

            string pre_cookie_url = String.Format(
                "http://as.aoshitang.com/getsession.xhtml?x={0}&isgameLogin=true&top=1&gameid=as&source=", 
                _rand.NextDouble());
            resp = TransferMgr.doGetPure(pre_cookie_url, ref cookies);
            pre_cookie_url = String.Format(
                "http://www.aoshitang.com/jsonp.action?jsoncallback=jsonp{0}&funName=checkLogin&x={1}", 
                TimeMgr.TimeStamp, _rand.NextDouble());
            resp = TransferMgr.doGetPure(pre_cookie_url, ref cookies);

            string loginurl = String.Format("http://www.aoshitang.com/jsonp.action?jsoncallback=jsonp{0}&funName=indexLogin&username={1}&password={2}",
                TimeMgr.TimeStamp, _username, _md5_password_lower);
            resp = TransferMgr.doGetPure(loginurl, ref cookies, "http://as.aoshitang.com/index.html");
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            string content = resp.getContent();
            //jsonp1390444740123({"ts":1390444974768,
            //  "current_user":{"uid":null,"createTime":"2013-04-17 09:23:37.0","emailValid":0,"idNum":null,"orignalEmail":"doomsword@163.com",
            //      "mobileValid":1,"id":2947589,"username":"doomsword","source":"aoshitang","idNumValid":0,"email":"doomsword@163.com","name":null,
            //      "mobile":"15810394205"},
            //  "success":true,"key":"9cd71f508619552f11512341557c9403"})
            content = content.Substring(content.IndexOf('(') + 1);
            content = content.Substring(0, content.IndexOf(')'));
            JsonTextParser parser = new JsonTextParser();
            JsonObjectCollection obj_login = (JsonObjectCollection)parser.Parse(content);
            IEnumerator<JsonObject> login_enumer = obj_login.GetEnumerator();
            string msg = ""; bool login_success = false;
            string key = "", userJson = ""; long ts = 0;
            while (login_enumer.MoveNext())
            {
                if (login_enumer.Current.Name == "ts")
                {
                    JsonNumericValue ts_item = login_enumer.Current as JsonNumericValue;
                    ts = (long)ts_item.Value;
                }
                if (login_enumer.Current.Name == "success") 
                {
                    JsonBooleanValue suc_item = login_enumer.Current as JsonBooleanValue;
                    login_success = (bool)suc_item.Value;
                }
                if (login_enumer.Current.Name == "msg")
                {
                    JsonStringValue msg_item = login_enumer.Current as JsonStringValue;
                    msg = msg_item.Value;
                }
                if (login_enumer.Current.Name == "key")
                {
                    JsonStringValue key_item = login_enumer.Current as JsonStringValue;
                    key = key_item.Value;
                }
                if (login_enumer.Current.Name == "current_user")
                {
                    JsonObjectCollection user_json_item = login_enumer.Current as JsonObjectCollection;

                    StringWriter sw = new StringWriter();
                    sw.Write("{");

                    for (int i = 0; i < user_json_item.Count; i++)
                    {
                        if (i > 0)
                        {
                            sw.Write(",");
                        }

                        user_json_item[i].WriteTo(sw);
                    }

                    sw.Write("}");

                    user_json_item.Name = string.Empty;
                    userJson = sw.ToString();
                }
            }
            if (!login_success || key == "" || userJson == "")
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                result.ErrMessage = msg;
                return result;
            }
            loginurl = "http://as.aoshitang.com/ssoLogin.xhtml";
            userJson = Uri.EscapeDataString(userJson);
            userJson = userJson.Replace("%20", "+");
            string data = String.Format("ts={0}&key={1}&userJson={2}&isgameLogin=true", ts, key, userJson);
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("X-Requested-With", "XMLHttpRequest");
            resp = TransferMgr.doPostPure(loginurl, data, ref cookies, "http://as.aoshitang.com/index.html", headers);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }
            content = resp.getContent();
            JsonObjectCollection obj_sso = (JsonObjectCollection)parser.Parse(content);
            IEnumerator<JsonObject> sso_enumer = obj_sso.GetEnumerator();
            while (sso_enumer.MoveNext())
            {
                if (sso_enumer.Current.Name == "playerid")
                {
                    JsonStringValue suc_item = sso_enumer.Current as JsonStringValue;
                    string playerid = suc_item.Value;
                    if (playerid == "")
                    {
                        result.StatusCode = LoginStatusCode.FailInLogin; return result;
                    }
                }
            }

            string redirecturl = String.Format("http://as.aoshitang.com/gm.xhtml?gid=as&server={0}", _acc.ServerId);
            resp = TransferMgr.doGetPure(redirecturl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGotoGameUrl; return result; }
            content = resp.getContent();
            //<script type="text/javascript">window.location.href = "http://s54.as.aoshitang.com/root/start.action?accid=4331571&accname=doomsword&serverid=54&tstamp=1390450397356&ticket=05e88e6e466ec1c4b5634884f4fd072c&fcm=0&mixflag=uoyoo";</script>
            Match match = Regex.Match(content, ".*?window\\.location\\.href.*?=.*?\"([^\"']*?)\".*");
            if (match == null || match.Groups == null || match.Groups.Count < 2)
            {
                result.StatusCode = LoginStatusCode.FailInGotoGameUrl; return result;
            }
            string starturl = match.Groups[1].Value;

            processStartGame(starturl, result, ref cookies);
            return result;
        }
    }
}
